<template>
  <div class="main-box">
    <TreeFilter
      title="桌台区域"
      label="name"
      :show-search="false"
      :data="treeFilterData"
      :default-value="initParam.typeId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="桌台列表"
        :columns="columns"
        :request-auto="false"
        :request-api="getFoodDeskList"
        :init-param="initParam"
        :data-callback="dataCallback"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
        @row-click="onRowClick"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" v-auth="'add'" :icon="CirclePlus" @click="openDialog('新增')"> 新增桌台 </el-button>
          <el-button type="primary" :icon="View" @click="openSeatCodeDialog('桌位二维码')"> 桌位二维码 </el-button>
          <el-button type="primary" :icon="View" @click="downloadCodeImage"> 下载二维码 </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-dropdown trigger="hover">
            <el-button type="primary">
              操作菜单
              <el-icon><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button v-auth="'view'" type="primary" link :icon="View" @click.stop="openDialog('查看', scope.row)">
                    查看
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button v-auth="'edit'" type="primary" link :icon="EditPen" @click.stop="openDialog('编辑', scope.row)">
                    编辑
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button v-auth="'delete'" type="primary" link :icon="Delete" @click.stop="deleteAccount(scope.row)">
                    删除
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ProTable>
      <BoardDialog ref="boardDialogRef" />
      <SeatCodeDialog ref="seatCodeDialogRef" />
    </div>
  </div>
</template>
<script setup lang="tsx" name="MethodManage">
import { onMounted, ref, reactive } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import BoardDialog from "@/views/restaurant/components/BoardDialog.vue";
import SeatCodeDialog from "@/views/restaurant/components/SeatCodeDialog.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
import {
  getFoodDeskCategoryList,
  getFoodDeskList,
  createFoodDesk,
  deleteFoodDesk,
  editFoodDesk,
  getFoodDeskQrCode,
  getEditFoodDesk,
  downloadCodeAPI
} from "@/api/modules/restaurant";
import { Restaurant } from "@/api/interface";
import Download from "@/layouts/components/Header/components/Download.vue";
import { downloadFile } from "@/utils/downLoad";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
// const { BUTTONS } = useAuthButtons();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ typeId: 0 });
const tbId = ref(0);
const treeFilterData = ref<any>([]);
// 新建加料默认参数
const defaultData = ref({
  status: 1,
  typeId: null,
  manQty: 4,
  fastFood: 0,
  sort: 1,
  deskFoodList: []
});
const rowData = ref({});

// 树形筛选切换
const changeTreeFilter = (val: number) => {
  // ElMessage.success("请注意查看请求参数变化 🤔");
  proTable.value!.pageable.pageNum = 1;
  initParam.typeId = val;
  defaultData.value.typeId = val;
  tbId.value = 0;
};

onMounted(() => {
  getTreeFilter();
});

const getTreeFilter = async () => {
  const { data } = await getFoodDeskCategoryList();
  treeFilterData.value = data.list;
  initParam.typeId = treeFilterData.value[0].id;
  defaultData.value.typeId = treeFilterData.value[0].id;
};

// 表格配置项
const columns: ColumnProps<Restaurant.ResFoodDeskList>[] = [
  { type: "radio", label: "", width: 54 },
  { type: "index", label: "序号", width: 65 },
  { prop: "name", sortable: true, label: "桌台名称", minWidth: 120, search: { el: "input" } },
  {
    prop: "typeId",
    label: "所属区域",
    sortable: true,
    minWidth: 120,
    enum: getFoodDeskCategoryList,
    fieldNames: { label: "name", value: "id" }
  },
  { prop: "manQty", label: "标准用餐人数", sortable: true, minWidth: 120 },
  {
    prop: "status",
    label: "使用状态",
    minWidth: 100,
    sortable: true,
    enum: [
      { name: "停用", id: 0 },
      { name: "正常", id: 1 }
    ],
    fieldNames: { label: "name", value: "id" }
  },
  { prop: "sort", label: "排序", sortable: true, width: 80 },
  { prop: "number", label: "数字助记码", sortable: true, minWidth: 100 },
  { prop: "operation", label: "操作", width: 128, fixed: "right" }
];

// 删除餐台
const deleteAccount = async (params: Restaurant.ResFoodDeskList) => {
  await useHandleData(deleteFoodDesk, { id: params.id }, `删除【${params.name}】餐台`);
  proTable.value?.getTableList();
};

// 打开 Dialog(新增、查看、编辑)
const boardDialogRef = ref<InstanceType<typeof BoardDialog> | null>(null);
const openDialog = async (title: string, row: Partial<Restaurant.ResFoodDeskList> = {}) => {
  if (title !== "新增") {
    const { data } = await getEditFoodDesk({ id: row.id });
    rowData.value = data;
  }
  const params = {
    title,
    isView: title === "查看",
    regData: treeFilterData.value,
    row: title === "新增" ? defaultData.value : rowData.value,
    api: title === "新增" ? createFoodDesk : title === "编辑" ? editFoodDesk : undefined,
    getTableList: proTable.value?.getTableList
  };
  boardDialogRef.value?.acceptParams(params);
};

const onRowClick = (row: Restaurant.ResFoodDeskList) => {
  tbId.value = row.id;
};

const dataCallback = (data: any) => {
  tbId.value = 0;
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

const seatCodeDialogRef = ref<InstanceType<typeof SeatCodeDialog> | null>(null);
const openSeatCodeDialog = (title: string) => {
  const params = {
    title,
    isView: false,
    typeId: initParam.typeId,
    id: tbId.value,
    api: getFoodDeskQrCode
  };
  seatCodeDialogRef.value?.acceptParams(params);
};

// 下载二维码
const downloadCodeImage = async () => {
  const res = await downloadCodeAPI({
    typeId: initParam.typeId,
    id: tbId.value
  });
  downloadFile(res.data);
};
</script>
